package com.atguigu.tingshu.album.config;

import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
@Configuration
public class MinioClientConfig {
    @Autowired
    private MinioConstantProperties minioConstantProperties;


    private MinioClient minioClient;

    /**
     * 初始化
     */
    @PostConstruct
    public void minioClient(){
        //初始化minio
         minioClient = MinioClient.builder()
                .endpoint(minioConstantProperties.getEndpointUrl())//设置minio IP地址
                .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())//用户名，密码
                .build();
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @SneakyThrows
    public String fileUpload(MultipartFile file){
        //校验桶是都存在
        if (!minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .build())) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .build());
        }
        //随机名字
        String name = UUID.randomUUID().toString().replace("-", "");
        //文件上传
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName()) //桶名字
                .contentType(file.getContentType())//文件类型
                .stream(file.getInputStream(), file.getSize(), -1)//文件内容大小，偏移量
                .object(name)
                .build());
        //返回获取文件访问地址 minio地址+"/"+桶名字（路径）+文件名
        return minioConstantProperties.getEndpointUrl()+"/"
                +minioConstantProperties.getBucketName()+"/"
                +name;
    }
}
